package com.evan.review.viewpager;

import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.RadioGroup;
import android.widget.Switch;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.evan.review.R;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;

/**
 * ViewPager2演示Activity
 * 展示ViewPager2的新特性和改进
 */
public class ViewPager2Activity extends AppCompatActivity {

    private static final String TAG = "ViewPager2Activity";
    private static final int PAGE_COUNT = 5; // 页面数量

    private ViewPager2 viewPager2;
    private TabLayout tabLayout;
    private RadioGroup rgOrientation; // 方向选择单选按钮组
    private Switch switchUserInput; // 用户输入开关
    private Button btnApplyTransform; // 应用转场效果按钮

    private int currentTransformIndex = 0; // 当前转场效果索引
    private final ViewPager2.PageTransformer[] transformers = {
            null, // 无转场效果
            (page, position) -> {
                // 淡入淡出效果
                final float normalizedPosition = Math.abs(Math.abs(position) - 1);
                page.setAlpha(normalizedPosition);
            },
            (page, position) -> {
                // 缩放效果
                final float MIN_SCALE = 0.85f;
                final float MIN_ALPHA = 0.5f;

                int pageWidth = page.getWidth();
                int pageHeight = page.getHeight();

                if (position < -1) { // [-Infinity,-1)
                    // 此页面在屏幕左侧远处
                    page.setAlpha(0f);
                } else if (position <= 1) { // [-1,1]
                    // 修改默认滑动过渡以同时缩小页面
                    float scaleFactor = Math.max(MIN_SCALE, 1 - Math.abs(position));
                    float vertMargin = pageHeight * (1 - scaleFactor) / 2;
                    float horzMargin = pageWidth * (1 - scaleFactor) / 2;
                    if (position < 0) {
                        page.setTranslationX(horzMargin - vertMargin / 2);
                    } else {
                        page.setTranslationX(-horzMargin + vertMargin / 2);
                    }

                    // 页面缩放(在MIN_SCALE和1之间)
                    page.setScaleX(scaleFactor);
                    page.setScaleY(scaleFactor);

                    // 页面透明度随尺寸变化
                    page.setAlpha(MIN_ALPHA + (scaleFactor - MIN_SCALE) / (1 - MIN_SCALE) * (1 - MIN_ALPHA));
                } else { // (1,+Infinity]
                    // 此页面在屏幕右侧远处
                    page.setAlpha(0f);
                }
            },
            (page, position) -> {
                // 深度效果
                if (position < -1) {
                    page.setAlpha(0);
                } else if (position <= 0) {
                    page.setAlpha(1);
                    page.setTranslationX(0);
                    page.setScaleX(1);
                    page.setScaleY(1);
                } else if (position <= 1) {
                    page.setAlpha(1 - position);
                    page.setTranslationX(page.getWidth() * -position);
                    float scale = 0.75f + 0.25f * (1 - Math.abs(position));
                    page.setScaleX(scale);
                    page.setScaleY(scale);
                } else {
                    page.setAlpha(0);
                }
            }
    };

    // 转场效果名称
    private final String[] transformerNames = {
            "无效果",
            "淡入淡出效果",
            "缩放效果",
            "深度效果"
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_viewpager2);

        initViews(); // 初始化视图
        setupViewPager(); // 设置ViewPager
        setupListeners(); // 设置监听器
    }

    /**
     * 初始化视图组件
     */
    private void initViews() {
        viewPager2 = findViewById(R.id.viewpager2);
        tabLayout = findViewById(R.id.tab_layout);
        rgOrientation = findViewById(R.id.rg_orientation);
        switchUserInput = findViewById(R.id.switch_user_input);
        btnApplyTransform = findViewById(R.id.btn_apply_transform);
    }

    /**
     * 设置ViewPager2及其适配器
     */
    private void setupViewPager() {
        // 设置适配器
        SimpleFragmentStateAdapter adapter = new SimpleFragmentStateAdapter(this);
        viewPager2.setAdapter(adapter);

        // 将TabLayout与ViewPager2关联
        new TabLayoutMediator(tabLayout, viewPager2, (tab, position) -> {
            tab.setText("页面 " + (position + 1));
        }).attach();

        // 注册页面变化回调
        viewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                Log.d(TAG, "onPageSelected: 位置=" + position);
            }
        });


        // 精致滑动
//        viewPager2.setUserInputEnabled(false);
    }

    /**
     * 设置各组件的事件监听器
     */
    private void setupListeners() {
        // 设置方向选择单选按钮组的监听器
        rgOrientation.setOnCheckedChangeListener((group, checkedId) -> {
            if (checkedId == R.id.rb_horizontal) {
                viewPager2.setOrientation(ViewPager2.ORIENTATION_HORIZONTAL);
                Toast.makeText(this, "已设置为水平方向", Toast.LENGTH_SHORT).show();
            } else if (checkedId == R.id.rb_vertical) {
                viewPager2.setOrientation(ViewPager2.ORIENTATION_VERTICAL);
                Toast.makeText(this, "已设置为垂直方向", Toast.LENGTH_SHORT).show();
            }
        });

        // 设置用户输入开关的监听器
        switchUserInput.setOnCheckedChangeListener((buttonView, isChecked) -> {
            viewPager2.setUserInputEnabled(isChecked);
            String message = isChecked ? "已启用用户输入" : "已禁用用户输入";
            Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
        });

        // 设置转场效果按钮的点击监听器
        btnApplyTransform.setOnClickListener(v -> {
            applyNextTransformation();
        });
    }

    /**
     * 应用下一个转场效果
     */
    private void applyNextTransformation() {
        currentTransformIndex = (currentTransformIndex + 1) % transformers.length;
        viewPager2.setPageTransformer(transformers[currentTransformIndex]);

        Toast.makeText(this, "已应用: " + transformerNames[currentTransformIndex],
                Toast.LENGTH_SHORT).show();

        btnApplyTransform.setText("转场效果: " + transformerNames[currentTransformIndex]);
    }

    /**
     * 简单的FragmentStateAdapter实现
     * ViewPager2专用适配器
     */
    private class SimpleFragmentStateAdapter extends FragmentStateAdapter {

        // 各页面的背景颜色
        private final int[] COLORS = new int[]{
                Color.parseColor("#F44336"), // 红色
                Color.parseColor("#9C27B0"), // 紫色
                Color.parseColor("#3F51B5"), // 靛蓝色
                Color.parseColor("#4CAF50"), // 绿色
                Color.parseColor("#FF9800")  // 橙色
        };

        SimpleFragmentStateAdapter(@NonNull FragmentActivity fragmentActivity) {
            super(fragmentActivity);
        }

        @NonNull
        @Override
        public Fragment createFragment(int position) {
            Log.d(TAG, "createFragment: 位置=" + position);
            return SimplePageFragment.newInstance(position + 1, COLORS[position]);
        }

        @Override
        public int getItemCount() {
            return PAGE_COUNT;
        }
    }
} 